import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/vpn_provider.dart';

/// 服务器诊断页面 - 用于检测和修复ID重复问题
class ServerDiagnosticPage extends StatelessWidget {
  const ServerDiagnosticPage({super.key});

  @override
  Widget build(BuildContext context) {
    final vpnProvider = Provider.of<VpnProvider>(context, listen: false);

    return Scaffold(
      appBar: AppBar(
        title: const Text('Server Diagnostics'),
        elevation: 0,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 说明卡片
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.info_outline,
                          color: Theme.of(context).colorScheme.primary,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          'What is this?',
                          style: Theme.of(context).textTheme.titleMedium?.copyWith(
                                fontWeight: FontWeight.bold,
                              ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 12),
                    const Text(
                      'This page helps you diagnose and fix server ID duplicate issues. '
                      'If you notice multiple servers being highlighted when connecting, '
                      'you may have duplicate server IDs.',
                      style: TextStyle(height: 1.5),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 检测按钮
            ElevatedButton.icon(
              onPressed: () {
                vpnProvider.diagnoseServerIds();
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('Check the console/debug output for results'),
                    duration: Duration(seconds: 3),
                  ),
                );
              },
              icon: const Icon(Icons.search),
              label: const Text('Diagnose Server IDs'),
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
              ),
            ),
            const SizedBox(height: 12),

            // 修复按钮
            ElevatedButton.icon(
              onPressed: () async {
                // 显示确认对话框
                final confirmed = await showDialog<bool>(
                  context: context,
                  builder: (context) => AlertDialog(
                    title: const Text('Fix Duplicate IDs'),
                    content: const Text(
                      'This will assign new unique IDs to servers with duplicate IDs. '
                      'This operation is safe and will not affect server configurations.\n\n'
                      'Do you want to continue?',
                    ),
                    actions: [
                      TextButton(
                        onPressed: () => Navigator.of(context).pop(false),
                        child: const Text('Cancel'),
                      ),
                      ElevatedButton(
                        onPressed: () => Navigator.of(context).pop(true),
                        child: const Text('Fix Now'),
                      ),
                    ],
                  ),
                );

                if (confirmed == true) {
                  await vpnProvider.fixDuplicateIds();
                  if (context.mounted) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('Server IDs fixed! Check console for details.'),
                        backgroundColor: Colors.green,
                        duration: Duration(seconds: 3),
                      ),
                    );
                  }
                }
              },
              icon: const Icon(Icons.build),
              label: const Text('Fix Duplicate IDs'),
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
                backgroundColor: Colors.orange,
                foregroundColor: Colors.white,
              ),
            ),
            const SizedBox(height: 24),

            // 服务器统计
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Server Statistics',
                      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.bold,
                          ),
                    ),
                    const SizedBox(height: 16),
                    Consumer<VpnProvider>(
                      builder: (context, provider, _) {
                        final servers = provider.servers;
                        final uniqueIds = servers.map((s) => s.id).toSet();
                        final groups = servers
                            .map((s) => s.group ?? 'Default')
                            .toSet()
                            .length;

                        return Column(
                          children: [
                            _buildStatRow(
                              'Total Servers',
                              servers.length.toString(),
                              Icons.dns,
                            ),
                            const Divider(height: 24),
                            _buildStatRow(
                              'Unique IDs',
                              uniqueIds.length.toString(),
                              Icons.fingerprint,
                            ),
                            const Divider(height: 24),
                            _buildStatRow(
                              'Groups',
                              groups.toString(),
                              Icons.folder,
                            ),
                            if (servers.length != uniqueIds.length) ...[
                              const Divider(height: 24),
                              _buildStatRow(
                                'Duplicate IDs',
                                (servers.length - uniqueIds.length).toString(),
                                Icons.warning,
                                color: Colors.red,
                              ),
                            ],
                          ],
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 24),

            // 说明卡片
            Card(
              color: Theme.of(context).colorScheme.surfaceVariant,
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.lightbulb_outline,
                          color: Theme.of(context).colorScheme.primary,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          'Recommendations',
                          style: Theme.of(context).textTheme.titleMedium?.copyWith(
                                fontWeight: FontWeight.bold,
                              ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 12),
                    _buildRecommendation(
                      '1. Run diagnostics first to check for issues',
                    ),
                    const SizedBox(height: 8),
                    _buildRecommendation(
                      '2. If duplicates found, use "Fix Duplicate IDs"',
                    ),
                    const SizedBox(height: 8),
                    _buildRecommendation(
                      '3. For best results, re-import subscriptions',
                    ),
                    const SizedBox(height: 8),
                    _buildRecommendation(
                      '4. Check console output for detailed results',
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatRow(String label, String value, IconData icon,
      {Color? color}) {
    return Row(
      children: [
        Icon(icon, color: color ?? Colors.grey[600], size: 20),
        const SizedBox(width: 12),
        Expanded(
          child: Text(
            label,
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[700],
            ),
          ),
        ),
        Text(
          value,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
      ],
    );
  }

  Widget _buildRecommendation(String text) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Icon(Icons.check_circle_outline, size: 16, color: Colors.green),
        const SizedBox(width: 8),
        Expanded(
          child: Text(
            text,
            style: const TextStyle(fontSize: 13, height: 1.4),
          ),
        ),
      ],
    );
  }
}
